<template>
  <el-form ref="formRef" :model="formData" label-width="120px">
    <el-row :gutter="20">
      <el-col
        v-for="(item, index) in config"
        :key="index"
        :span="item.span || 6"
      >
        <el-form-item :label="item.label">
          <!-- 输入框 -->
          <el-input
            v-if="item.type === 'input'"
            v-model="formData[item.field]"
            :placeholder="item.placeholder"
            clearable
          />

          <!-- 选择器 -->
          <el-select
            v-else-if="item.type === 'select'"
            v-model="formData[item.field]"
            :placeholder="item.placeholder"
            clearable
          >
            <el-option
              v-for="opt in item.options"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>

          <!-- 级联选择器 -->
          <el-cascader
            v-else-if="item.type === 'cascader'"
            v-model="formData[item.field]"
            :options="item.options"
            :props="item.props"
            :placeholder="item.placeholder"
            clearable
          />

          <!-- 日期范围选择 -->
          <el-date-picker
            v-else-if="item.type === 'daterange'"
            v-model="formData[item.field]"
            type="daterange"
            range-separator="-"
            :start-placeholder="item.startPlaceholder || '开始日期'"
            :end-placeholder="item.endPlaceholder || '结束日期'"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';

const props = defineProps({
  config: {
    type: Array,
    required: true,
    validator: (value) => {
      return value.every((item) =>
        ['input', 'select', 'cascader', 'daterange'].includes(item.type),
      );
    },
  },
});

const emit = defineEmits(['submit']);

// 初始化表单数据
const initFormData = () => {
  const data = {};
  props.config.forEach((item) => {
    switch (item.type) {
      case 'input':
      case 'select':
        data[item.field] = '';
        break;
      case 'cascader':
      case 'daterange':
        data[item.field] = [];
        break;
    }
  });
  return data;
};

const formData = reactive(initFormData());

// 处理搜索
const handleSearch = () => {
  emit('submit', formData);
};

// 处理重置
const handleReset = () => {
  Object.assign(formData, initFormData());
};

// 监听config变化重新初始化表单
watch(
  () => props.config,
  () => {
    Object.assign(formData, initFormData());
  },
  { deep: true },
);
</script>
